<?php

namespace app\common\library;

use app\common\model\UrlPerson;
use app\common\model\UrlPublic;
use app\common\model\Type;
use think\db;

class YuDa
{
    const VERSION = '6.0.5';

    protected $errorString = '';

    public static $instance ;

    /**
     * @title 单例调用
     * @description 单例调用
     * @author Admin ldy
     * @time 2018/9/25  12:22
     */
    public static function getInstance(){
        if (YuDa::$instance == null){
            YuDa::$instance = new \app\common\library\YuDa;
            return YuDa::$instance;
        }else{
            return YuDa::$instance;
        }
    }

    public function __construct(){
        //初始化
    }

    public function setErrorString($msg){
        $this->errorString = $msg;
    }

    public function getErrorString(){
        return $this->errorString;
    }

    public function handleYudata($url){
        //检查是否为空
        if (!$url || empty($url)){
            $this->setErrorString('传入参数不能为空！');
            return $this->errorString;
        }
        //检查长度是否超过http
        ///去空
        $urlstring = preg_replace('# #','',$url);
        //算长度
        $len = mb_strlen($urlstring,"utf-8");
        if ($len<=4){
            $this->setErrorString('传入参数有误！');
            return $this->errorString;
        }
        //判断是否http开头，如果不是则自动拼接一个http://
        $str = substr($urlstring,0,4);
        if ($str != 'http'){
            $urlstring = 'http://'.$urlstring;
        }
        return $urlstring;
    }

    public static function addPublicUrl($url,$token,$type='auto',$option=array()){
        $da = YuUtil::json_to_array(json_decode(YuUtil::getFormatUrlParams($url,$token)));
        if ($type=='nonautomatic'){
            //如果是手动提交标题，则不需要自动获取，优化性能
            $da['title_auto'] = $option['title_auto'];
            $da['type_auto'] =  $option['type_auto'];
            $da['url_data_json'] = $option['url_data_json'];
        }
        try {
            //检查是否已经存在该url
            $urlpublic = UrlPublic::field('url,status_is_use,version,num_read_all,num_like,id,socre,num_collecton,num_open_pv')->where($da['con'])->find();
            if ($urlpublic) {
                //存在则只修改收藏数，而不添加一条新纪录
                $urlpublic->status_is_use = '0';//？
                $urlpublic->version = YuUtil::addIntValue($urlpublic->version);
                $urlpublic->socre =YuUtil::addIntValue($urlpublic->socre);
                $urlpublic->num_read_all = YuUtil::addIntValue($urlpublic->num_read_all);
                $urlpublic->num_like = YuUtil::addIntValue($urlpublic->num_like);
                $urlpublic->num_collecton = YuUtil::addIntValue($urlpublic->num_collecton);
                $urlpublic->num_open_pv = YuUtil::addIntValue($urlpublic->num_open_pv);
            } else {
                //不存在的，就新增
                $urlpublic = new UrlPublic();
                $urlpublic->url = $da['url'];
                $urlpublic->url_scheme = $da['scheme'];
                $urlpublic->url_host = $da['host'];
                $urlpublic->url_path = $da['url_path'];
                $urlpublic->key = $da['key'];
                $urlpublic->version = '01';
                $urlpublic->socre = '50';
                $urlpublic->num_read_all = 1;
                $urlpublic->num_like = 1;
                $urlpublic->num_collecton = 1;

                if ($type == 'auto') {
                    //如果是自动获取标题，则异步执行
                    //访问一次，获取title数据(次要数据插入操作，异步执行，优化速度)
                    //方法1，自己简单的实现异步调用
//                $apiString = '/api/yudata/yuDetail/';
//                $this->asynDoByUrl($apiString,array('token'=>$da['token'],'u'=>$da['url']));
                    //方法2，使用think-queue组件异步执行任务，可监控
//                $jobHandlerClassName  = 'app\common\job\AddAutoTitle';
//                $jobQueueName  	  = "yuJobQueue";
//                $jobData       	  = [ 'token' => $da['token'], 'u' => $da['url']] ;
//                $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                    //方法3，封装使用，使用内存空间换取响应时间
                    $jobHandlerClassName = 'app\common\job\AddAutoTitle';
                    $jobData = ['token' => $da['token'], 'u' => $da['url']];
                    $isPushed = YuUtil::postMsg($jobHandlerClassName, $jobData,'yuJobQueueTime');
                    if ($isPushed) {
                        $pushTime = date('Y-m-d H:i:s') . " a new AddAutoTitle Job is Pushed to the MQ" . "<br>";
                    } else {
                        $pushTime = 'Oops, something went wrong.';
                    }
                    $urlpublic->desc = $pushTime;
                }
                if ($type == 'nonautomatic') {
                    //手动提交的，新增的时候，直接插入标题数据
                    $urlpublic->title_auto = YuUtil::format_empty($da['title_auto']);
                    $urlpublic->type_auto = YuUtil::format_empty($da['type_auto']);
                    $urlpublic->url_data_json = YuUtil::format_empty($da['url_data_json']);
                }
            }
            $re = $urlpublic->save();
            if ($re) {
                return new ReSuccess('成功',$da);
            } else {
                return new ReFail(ErrorType::ADD_DATA_FAILED,'到底哪里失败了？');
            }
        }catch (Exception $e){
            return new ReFail(ErrorType::ADD_DATA_FAILED,$e->getTraceAsString());
        }
    }


    public static function addPersonUrl($url,$token,$options=array()){
        $da = YuUtil::json_to_array(json_decode(YuUtil::getFormatUrlParams($url,$token)));
        //检查是否已经存在该url
        $urlpublic = UrlPublic::field('title_auto,id,socre,num_collecton,status_is_use')->where($da['con'])->find();
        if (!$urlpublic) {
            //不存在的先插入到公共url后，在给个人添加？
            //抛出错误
            return new ReFail(ErrorType::DATA_EXCEPTION,'该url不存在哈！');
        }
        //存在父类的直接复制数据给个人
        //是否存在类型？（无法自动插入，因为不存在数据）
        $type = Type::field('id')->where(array('id' => $options['typeid']))->find();
        if (!$type) {
            return new ReFail(ErrorType::DATA_EXCEPTION,'类型不存在哈！');
        }
        $where=array(
            'base_url_id'=>$urlpublic->id,
            'user_id'=>YuUtil::getStringByKey('uid',$options),
        );
        $urlperson = UrlPerson::field('type_id,desc,nickname,id,base_url_id,num_read,num_collection,num_like,socre,version')->where($where)->find();
        if ($urlperson){
            //存在个人的URL，修改个人的数据
            $urlperson->num_read = YuUtil::addIntValue($urlperson->num_read);
            $urlperson->num_collection = YuUtil::addIntValue($urlperson->num_collection);
            $urlperson->num_like = YuUtil::addIntValue($urlperson->num_like);
            $urlperson->socre = YuUtil::addIntValue($urlperson->socre);
            $urlperson->version = YuUtil::addIntValue($urlperson->version);
            $re = $urlperson->save();
        }else{
            //不存在个人的URL，开始新增
            $urlperson = new UrlPerson();
            $urlperson->base_url_id = $urlpublic->id;
            $urlperson->status_is_detele = $urlpublic->status_is_use;
            $urlperson->num_read = 1;
            $urlperson->num_collection = 1;
            $urlperson->num_like = 1;
            $urlperson->socre = 50;
            $urlperson->version = 1;
            $urlperson->type_id = YuUtil::getStringByKey('typeid',$options);
            $urlperson->user_id = YuUtil::getStringByKey('uid',$options);
            $urlperson->parent_id = 0;
            $urlperson->desc = YuUtil::getStringByKey('desc',$options);//$options['desc']
            $urlperson->nickname = YuUtil::getStringByKey('nickname',$options);//$options['nickname'];
            $urlperson->keyword = YuUtil::getStringByKey('key_word',$options);//$options['key_word'];
            $re = $urlperson->save();
        }
        if ($re){
            return new ReSuccess('新增成功',$urlperson);
        }else{
            return new ReFail(ErrorType::ADD_DATA_FAILED,'插入数据库失败！');
        }
    }

    public static function checkPersonUrlExist($public_url_id){
        $urlperson = UrlPerson::field('id,base_url_id')->where(array('base_url_id'=>$public_url_id))->find();
        if ($urlperson){
            return new ReSuccess('已存在个人的URL了');
        }else{
            return new ReFail('不存在个人的URL');
        }
    }


    public static function getTypeStringById($typeid,$uid){
        $con = array(
            'uid' => $uid,
        );
        $typearr = Db::table('scj_type')->where($con)->select();
        if ($typearr) {
            $list = YuUtil::getParent($typearr, $typeid);
            $str = '';
            if (!$list){
                return new ReFail(ErrorType::DATA_EXCEPTION);
            }
            foreach (array_reverse($list) as $item) {
                $str .= $item['name'] . ' ';
            }
            $resultString=$str;
        }else{
            return new ReFail(ErrorType::ACTION_FAILED);
        }
        return new ReSuccess('成功',$resultString);
    }

    /**
     * @title 获取用户的url数
     * @description 获取用户的url数
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @time 2018/10/24  16:29
     * @return ReFail|ReSuccess
     */
    public static function getPersonUrlCountByUerId($uid){
        $con = array(
            'user_id' => $uid,
            'status_is_detele'=>0,//正常状态的
        );
        $count = UrlPerson::where($con)->count();
        if ($count){
            return new ReSuccess('查询数据成功！',$count);
        }else{
            return new ReFail(ErrorType::GET_DATA_FAILED);
        }
    }

    /**
     * @title 获取用户的type数
     * @description 获取用户的type数
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:
     * @time 2018/10/24  16:32
     * @return ReFail|ReSuccess
     */
    public static function getPersonTypeCountByUerId($uid){
        $con = array(
            'uid' => $uid,
        );
        $count = Type::where($con)->count();
        if ($count){
            return new ReSuccess('查询数据成功！',$count);
        }else{
            return new ReFail(ErrorType::GET_DATA_FAILED);
        }
    }

    /**
     * @title 根据用户格式化后的数据，添加到数据库
     * @description 根据用户格式化后的数据，添加到数据库
     * @author Admin ldy
     * @param name:$uid  type:string require:1 default:1 desc:用户id
     * @param name:$arr  type:string require:1 default:1 desc:用户数据
     * @return ReFail|ReSuccess
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @time 2018/11/6  17:58
     */
    public static function addUserDataByUploadJson($uid,$arr){
//        $message = '后台正在解析数据……';
//        //推送消息给前端，前端自动刷新
//        \app\common\library\YuPust::pushMsgToUid($uid,$message);
        //理论上应该将数据传递到后台操作，而且不成功的话要记录下用户的数据！！
        $checkFirstTypeRe = \app\common\library\YuUnDeleteType::checkFirstTypeByUid($uid);
        if (!$checkFirstTypeRe->getStatus()){
            return new ReFail($checkFirstTypeRe->getMsg());
        }
        $len = count($arr);
        if ($len>0){
            $browserResult = YuUnDeleteType::getUserBrowserTypeIdByUserId($uid);
            if (!$browserResult->getStatus()){
                return new ReFail(ErrorType::ACTION_FAILED,'获取浏览器目录失败！YuUnDeleteType::getUserBrowserTypeIdByUserId');
            }
            $temarr1 = $browserResult->getData();
            $userBrowserTypeId = $temarr1['id'];
            kh('$userBrowserTypeId: '.$userBrowserTypeId);

            $re = \app\common\library\YuUnDeleteType::getFolder($uid,$arr,$userBrowserTypeId);

            if ($re){
                return new ReSuccess('数据操作成功！',$len);
            }else{
                return new ReFail(ErrorType::ACTION_FAILED);
            }
        }else{
            return new ReFail(ErrorType::DATA_EXCEPTION);
        }

    }




}
